import {API_URL} from '@/env';


const http = (options) => {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: '加载中...',
            mask: options.load || false // 默认遮罩出现可以继续操作
        });
        uni.request({
            url: (options.baseURL || API_URL) + options.url,
            method: options.method || 'POST', // 默认为POST请求
            data: options.data, //请求超时在manifest.json配置
            header: {'Content-Type': CONTENT_TYPES[options.header] || CONTENT_TYPES['json'], "Access-Control-Allow-Origin":"*"},

            // 接口请求成功
            success: res => {
                setTimeout(() => {
                    uni.hideLoading();
                }, 500)
                let data = res.data;
                resolve(data)
            },

            // 接口请求失败
            fail: (err) => {
                uni.hideLoading();
                uni.showToast({
                    title: '网络请求异常',
                    icon: 'none'
                });
                reject({code: 1000, message: '网络请求异常'});
            },

            // 接口请求结束
            complete: () => {
                // console.debug('<<<<<<<<接口请求结束');
            }

        });
    })

};

const CONTENT_TYPES = {
    'form': 'application/x-www-form-urlencoded',
    'multipart': 'multipart/form-data',
    'json': 'application/json'
};

['get', 'post', 'put', 'delete'].forEach(method => {
    http[method] = (url, data = {}, header = {}, options = {}) => {
        options = {url, method, data, header, ...options};
        return http(options);
    };
});

export default http;
